<template>
  <div class="text-wrapper w1 h1" ref="wrapper">
    <div class="text-inner" ref="inner">
      <span>{{text}}</span>
    </div>
  </div>
</template>
<script>
import { setInterval, clearInterval } from 'timers'
export default {
  props: {
    text: {
      type: String,
      default: ''
    }
  },
  data: () => ({ widthDifference: 0, timer: null }),
  mounted() {
    this.getWidthDifference()
    window.addEventListener('resize', this.getWidthDifference)
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    window.removeEventListener('resize', this.getWidthDifference)
  },
  methods: {
    getWidthDifference() {
      this.$nextTick(() => {
        let wrapperWidth = this.$refs.wrapper.clientWidth
        let innerWidth = this.$refs.inner.clientWidth
        this.widthDifference = innerWidth - wrapperWidth
      })
    },
    slideText() {
      // inenr-dom 位移距离 自身宽度，就要为0
      if (this.timer) {
        clearInterval(this.timer)
      }
      let innerDom = this.$refs.inner
      let innerWidth = innerDom.clientWidth
      // let percent = innerWidth / 2
      let step = 0
      this.timer = setInterval(() => {
        let distance = (step -= 5)
        innerDom.style.transform = 'translateX(' + distance + 'px)'
        if (distance <= -innerWidth) {
          step = 0
        }
      }, 1000)
    },
    textCenter() {
      let innerDom = this.$refs.inner
      innerDom.style.transform = 'translateX(-50%)'
    }
  },

  watch: {
    widthDifference() {
      if (this.widthDifference > 0) {
        this.slideText()
      } else {
        if (this.timer) {
          clearInterval(this.timer)
        }
        this.textCenter()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.text-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  .text-inner {
    display: inline-block;
    position: absolute;
    // left: 0;
    // 这里的动画时间要和定时器时间一致
    transition: all linear 1s;
    left: 50%;
    transform: translateX(-50%);
    white-space: nowrap;
  }
}
</style>
